<?php

namespace app\api\controller\deerhome\shop;

use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Db;

/**
 * 首页接口
 */
class Wechat extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {

        $config = [
            'app_id' => 'wx2c33e44bd0c7d647',
            'secret' => 'b6778d75b052ed5e01dfdaf9deab2034',
            'token' => 'gongxiduo',
        ];

        $app = Factory::officialAccount($config);



        $app->server->push(function ($message) {
            $this->qqq($message);
            switch ($message['MsgType']) {
                case 'event':
                    return '您好，欢迎您的到来！';
                    break;
                case 'text':
                    $this->_dealTxtmsg($message);
                    break;
                case 'image':
//                return '收到图片消息';
                    break;
                case 'voice':
//                return '收到语音消息';
                    break;
                case 'video':
//                return '收到视频消息';
                    break;
                case 'location':
//                return '收到坐标消息';
                    break;
                case 'link':
//                return '收到链接消息';
                    break;
                default:
//                return '收到其它消息';
                    break;
            }
            return '';
        });

        $response = $app->server->serve();
        // 将响应输出
        $response->send();




    }


    public function _dealTxtmsg($message)
    {

        if($message['Content'] == '接收模版消息'){

            $openid = $message['FromUserName'];
            $info = Db::name('wechat')->where('openid',$openid)->find();
            $this->qqq($openid);
            if(!empty($info)){
                Db::name('wechat')->where('openid',$openid)->update(['updatetime'=>time()]);
            }else{
                Db::name('wechat')->insertGetId(['openid'=>$openid,'createtime'=>time(),'updatetime'=>time()]);
            }
        }



    }


    public function qqq($request_data){
        try {
            $tmp= array();
            $tmp["content"] = json_encode($request_data,JSON_UNESCAPED_UNICODE);
            $tmp["name"] = 'DemosmsSend';
            $tmp["create_time"] = date("Y-m-d H:i:s");
            db('log_test',[],"qqq")->insertGetId($tmp);
        } catch (\Exception $e) {
            $tmp= array();
            $tmp["content"] = "插入错误";
            $tmp["name"] = 'DemosmsSend';
            $tmp["create_time"] = date("Y-m-d H:i:s");
            db('log_test',[],"qqq")->insertGetId($tmp);
        }
    }
}
